package com.qiongqi.datadir.controller;

// Ruoyi相关导入
import com.qiongqi.datadir.common.BaseController;
import com.qiongqi.datadir.config.DataDirConfig;
import com.qiongqi.datadir.utils.file.PdfRenderingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.io.File;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * PDF预览控制器
 */
@Slf4j
@Controller
@RequestMapping("/pdf")
public class PdfPreviewController extends BaseController {

    @Autowired
    private DataDirConfig dataDirConfig;

    /**
     * 打开PDF预览页面
     */
    @GetMapping
    public String view(Model model, @RequestParam(value = "pdfUrl", required = false) String pdfUrl) {
        model.addAttribute("pdfUrl", pdfUrl);
        return "view"; // 对应templates/pdf/preview.html
    }

    /**
     * 渲染PDF为图片
     */
    @PostMapping("/render")
    @ResponseBody
    public void renderPdf(
            @RequestParam String pdfUrl,
            @RequestParam(defaultValue = "0") int pageIndex,
            HttpServletRequest request,
            HttpServletResponse response) {

        try {
            // 从Minio下载PDF到临时文件
            File tempPdfFile = downloadPdfFromMinio(pdfUrl);

            // 获取当前用户信息（根据Ruoyi框架调整）
            String username = dataDirConfig.getName();
            String userIp = getClientIP(request);

            // 渲染PDF页面为带水印的图片
            byte[] imageData = PdfRenderingUtils.renderPageWithWatermark(
                    tempPdfFile.getAbsolutePath(),
                    pageIndex,
                    username,
                    userIp,
                    1000 // 最大宽度
            );

            // 设置响应头
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "inline; filename=\"preview.jpg\"");

            // 写入响应流
            response.getOutputStream().write(imageData);
            response.getOutputStream().flush();

            // 删除临时文件
            tempPdfFile.delete();

        } catch (Exception e) {
            log.error("PDF渲染失败", e);
            throw new RuntimeException("PDF渲染失败: " + e.getMessage());
        }
    }

    /**
     * 从Minio下载PDF到临时文件
     */
    private File downloadPdfFromMinio(String pdfUrl) throws Exception {
        // 创建临时文件
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
                .withZone(ZoneId.systemDefault());
        String timestampStr = formatter.format(Instant.now());
        File tempFile = File.createTempFile("pdf_preview_" + timestampStr, ".pdf");
        tempFile.deleteOnExit();

        try (InputStream in = new URL(pdfUrl).openStream()) {
            Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        return tempFile;
    }

    /**
     * 获取客户端IP
     */
    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}